<template>
  <div id="user-list">
    <!-- 顶部大标题和统计区 -->
    <div class="header-section">
      <div class="header-content">
        <div class="title-section">
          <h2 class="page-title">
            <i class="el-icon-user"></i> 用户列表管理
          </h2>
          <p class="page-subtitle">管理平台所有用户信息</p>
        </div>
        <div class="total-count">
          <div class="count-card">
            <span class="count-label">总用户数</span>
            <span class="count-value">{{ total }}</span>
          </div>
        </div>
      </div>
    </div>
    <el-card>
      <!-- 查询区卡片 -->
      <div class="search-filter-card">
        <div style="display: flex; align-items: center; justify-content: flex-end; gap: 10px;">
          <el-input v-model="search" placeholder="查询" style="width: 200px;" />
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button
            type="danger"
            @click="handleBatchDelete"
            :disabled="multipleSelection.length === 0"
          >
            批量删除
          </el-button>
        </div>
      </div>
      <!-- 表格和分页 -->
      <div class="data-table-card">
        <el-table
          :data="pagedUsers"
          style="width: 100%; background: #fff0f6;"
          @selection-change="handleSelectionChange"
          ref="userTable"
        >
          <el-table-column type="selection" width="50" />
          <el-table-column label="山行者号" width="100">
            <template #default="scope">
              <span>{{ getRandomNo(scope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="用户" min-width="200" align="left">
            <template #default="scope">
              <div style="display: flex; align-items: center; gap: 14px; justify-content: flex-start;">
                <el-avatar
                  :src="scope.row.userAvatar"
                  size="large"
                  style="width: 48px; height: 48px; font-size: 22px;"
                >
                  {{ scope.row.userName ? scope.row.userName.charAt(0) : '' }}
                </el-avatar>
                <span style="font-weight: 700; font-size: 18px; color: #222;">{{ scope.row.userName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="gender" label="性别" width="60" header-cell-style="{ whiteSpace: 'nowrap' }">
            <template #default="scope">
              <span v-if="scope.row.gender === 1">男</span>
              <span v-else-if="scope.row.gender === 2">女</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column prop="contactPhone" label="联系电话" min-width="130" />
          <el-table-column prop="userEmail" label="邮箱" min-width="160" show-overflow-tooltip align="left" />
          <el-table-column label="操作" width="180" align="left">
            <template #default="scope">
              <div style="display: flex; gap: 6px; align-items: center; justify-content: flex-start;">
                <el-button size="small" type="primary" @click="handleDetail(scope.row)">详情</el-button>
                <el-button size="small" class="delete-btn" @click="handleDelete(scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
            :page-sizes="[10, 20, 50]"
          />
        </div>
      </div>
    </el-card>
    <el-dialog v-model="detailDialogVisible" title="用户详情" width="420px" :close-on-click-modal="true">
      <div style="text-align:center;margin-bottom:18px;">
        <el-avatar :src="detailUser.userAvatar" size="large" style="width:80px;height:80px;margin-bottom:10px;box-shadow:0 2px 8px #e0e7ef;" />
        <div style="font-size:20px;font-weight:bold;margin-top:6px;">{{ detailUser.userName }}</div>
        <div style="color:#888;font-size:14px;">{{ detailUser.signature }}</div>
      </div>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="山行者号">{{ getRandomNo(detailUser) }}</el-descriptions-item>
        <el-descriptions-item label="性别">
          <span v-if="detailUser.gender === 1">男</span>
          <span v-else-if="detailUser.gender === 2">女</span>
          <span v-else>--</span>
        </el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ detailUser.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ detailUser.userEmail }}</el-descriptions-item>
        <el-descriptions-item label="个人简介">{{ detailUser.personalIntroduction }}</el-descriptions-item>
        <el-descriptions-item label="出生日期">{{ detailUser.dateOfBirth }}</el-descriptions-item>
        <el-descriptions-item label="注册时间">{{ formatDate(detailUser.registrationTime) }}</el-descriptions-item>
        <el-descriptions-item label="修改时间">{{ formatDate(detailUser.modificationTime) }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false" type="primary">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Lightning } from '@element-plus/icons-vue'
import axios from 'axios'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
dayjs.extend(utc)

const search = ref('')
const users = ref([])
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
const editDialogVisible = ref(false)
const editUser = ref({})
const multipleSelection = ref([])
const userTable = ref(null)
const detailDialogVisible = ref(false)
const detailUser = ref({})

const pagedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return users.value.slice(start, end)
})

async function fetchUsers() {
  const res = await axios.get('http://localhost:8080/mw/UserList', {
    params: {
      keyword: search.value
    }
  })
  users.value = res.data
  total.value = users.value.length

  // 这里加调试代码
  if (users.value.length > 0) {
    console.log('registrationTime:', users.value[0].registrationTime)
    console.log('dayjs:', dayjs(users.value[0].registrationTime).isValid())
    console.log('dayjs.utc:', dayjs.utc(users.value[0].registrationTime).isValid())
    console.log('new Date:', new Date(users.value[0].registrationTime))
  }

  console.log('全部用户数据:', users.value)
  users.value.forEach(u => {
    console.log('reg:', u.registrationTime, typeof u.registrationTime)
    console.log('mod:', u.modificationTime, typeof u.modificationTime)
  })
}

function handleSearch() {
  fetchUsers()
}
function handleDetail(row) {
  detailUser.value = { ...row }
  detailDialogVisible.value = true
}
function handleDelete(row) {
  ElMessageBox.confirm(`确定要删除用户 ${row.userName} 吗？`, '提示', {
    type: 'warning',
  }).then(async () => {
    // 调用后端删除接口
    const res = await axios.get(`http://localhost:8080/mw/deleteUserById?id=${row.userId}`)
    if (res.data === 1) {
      // 删除成功，前端移除
      users.value = users.value.filter(user => user.userId !== row.userId)
      total.value = users.value.length
      ElMessage.success('删除成功')
    } else {
      ElMessage.error('删除失败，用户不存在或已被删除')
      // 可选：fetchUsers() 强制刷新
    }
  })
}
function handleSizeChange(size) {
  pageSize.value = size
  // fetchUsers() // 后端无分页，暂不刷新
}
function handlePageChange(page) {
  currentPage.value = page
  // fetchUsers() // 后端无分页，暂不刷新
}

function formatDate(rowOrValue, column, cellValue) {
  // 如果只传一个参数，说明是弹窗用的
  let value
  if (arguments.length === 1) {
    value = rowOrValue
  } else {
    value = cellValue
  }
  if (!value) return ''
  const d = new Date(value)
  if (isNaN(d.getTime())) return 'Invalid Date'
  return d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0') +
    ' ' + String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0') + ':' + String(d.getSeconds()).padStart(2, '0')
}

function handleSelectionChange(val) {
  multipleSelection.value = val
}

async function handleBatchDelete() {
  if (multipleSelection.value.length === 0) return
  ElMessageBox.confirm(
    `确定要批量删除这 ${multipleSelection.value.length} 个用户吗？`,
    '批量删除',
    { type: 'warning' }
  ).then(async () => {
    for (const user of multipleSelection.value) {
      await axios.get(`http://localhost:8080/mw/deleteUserById?id=${user.userId}`)
    }
    users.value = users.value.filter(
      user => !multipleSelection.value.some(sel => sel.userId === user.userId)
    )
    total.value = users.value.length
    multipleSelection.value = []
    if (userTable.value) userTable.value.clearSelection()
    ElMessage.success('批量删除成功')
  })
}

// 添加图片URL验证函数
function isValidImageUrl(url) {
  try {
    new URL(url)
    return true
  } catch {
    return false
  }
}

function handleAvatarSuccess(response) {
  editUser.value.userAvatar = response.url // 这里的 url 是后端返回的图片访问路径
}

// 记录每个用户的编号，保证同一次渲染不会重复
const randomNoMap = new Map()
function getRandomNo(row) {
  if (randomNoMap.has(row.userId)) {
    return randomNoMap.get(row.userId)
  }
  // 生成5位随机数
  let no
  do {
    no = 'M' + Math.floor(Math.random() * 90000 + 10000)
  } while ([...randomNoMap.values()].includes(no))
  randomNoMap.set(row.userId, no)
  return no
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
#user-list {
  padding: 32px;
  background: #f5f6fa;
}
.el-card {
  background: #fff;
  border: none;
  box-shadow: 0 2px 8px 0 rgba(0,0,0,0.04);
  border-radius: 12px;
}
.el-table {
  background: #fff;
  border-radius: 22px;
  overflow: hidden;
  border: 1.5px solid #f0f1f5;
  box-shadow: none;
}
.el-table th, .el-table td {
  background: #fff !important;
  color: #333;
  font-weight: 500;
  text-align: center;
  height: 64px;
  padding: 16px 0;
}
.el-table th {
  background: #f3f7fb !important;
  font-weight: 700;
  color: #2d3a4a;
  text-align: center;
  font-size: 18px;
  letter-spacing: 1px;
}
.el-table__row {
  transition: background 0.2s;
}
.el-table__row:hover {
  background: #eaf4ff !important;
}
.el-table--striped .el-table__body tr.el-table__row--striped td {
  background: #f7f8fa !important;
}
.el-input {
  border-radius: 8px;
}
.el-pagination {
  margin-top: 8px;
  display: flex;
  justify-content: center;
}
.edit-btn, .delete-btn {
  border-radius: 20px;
  margin-left: 6px;
  font-size: 15px;
  padding: 6px 20px;
  box-shadow: none;
  transition: box-shadow 0.18s, background 0.18s, color 0.18s;
}
.edit-btn {
  background: #f5faff;
  border: 1.5px solid #3370ff;
  color: #3370ff;
}
.edit-btn:hover {
  background: #3370ff;
  color: #fff;
  box-shadow: 0 2px 8px #b3d4fc44;
}
.delete-btn {
  background: #fff6f6;
  border: 1.5px solid #f56c6c;
  color: #f56c6c;
}
.delete-btn:hover {
  background: #f56c6c;
  color: #fff;
  border-color: #f56c6c;
  box-shadow: 0 2px 8px #f56c6c33;
}
.el-button--primary {
  background: linear-gradient(135deg, #5fa8e6 0%, #3182ce 100%);
  border: none;
  color: #fff;
  border-radius: 20px;
  box-shadow: none;
  font-size: 15px;
  padding: 6px 20px;
}
.el-button--primary:hover {
  opacity: 0.95;
  box-shadow: 0 2px 8px #5fa8e644;
}
.header-section {
  background: linear-gradient(135deg, #a0c4e4 0%, #7fa8d1 100%);
  padding: 20px 25px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(160, 196, 228, 0.2);
  margin-bottom: 24px;
  color: #2c3e50;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section .page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 10px;
}
.title-section .page-title i {
  font-size: 28px;
  color: #2c3e50;
}
.title-section .page-subtitle {
  margin: 5px 0 0;
  font-size: 14px;
  color: #4a5568;
}

.total-count .count-card {
  background: rgba(255, 255, 255, 0.7);
  padding: 12px 20px;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  border: 1px solid #e2e8f0;
}
.total-count .count-label {
  font-size: 14px;
  margin-bottom: 5px;
  color: #4a5568;
}
.total-count .count-value {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
}

/* 查询区卡片 */
.search-filter-card {
  background-color: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

/* 表格卡片 */
.data-table-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  margin-bottom: 20px;
}

/* 分页美化 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 15px 0;
}

:deep(.el-pagination) {
  .btn-prev, .btn-next {
    border-radius: 8px;
    border: 1px solid #e2e8f0;
  }
  .el-pager li {
    border-radius: 8px;
    border: 1px solid #e2e8f0;
    margin: 0 4px;
    background: white;
    &.active {
      background: linear-gradient(135deg, #4299e1 0%, #3182ce 100%);
      color: white;
    }
  }
  .el-pagination__jump .el-input__inner {
    border-radius: 8px;
  }
}
</style>
